import Foundation

extension String {
    func extractJSON() -> String? {
        guard let start = self.range(of: "```json")?.upperBound,
              let end = self.range(of: "```", range: start..<self.endIndex)?.lowerBound
        else { return nil }

        let json = self[start..<end]
            .trimmingCharacters(in: .whitespacesAndNewlines)

        return String(json)
    }
}

class ReceiptAnalyzer {
    static let shared = ReceiptAnalyzer()

    func analyzeReceipt(imageURL: String) async throws -> ExpenseAIResponse {
        let rawText = try await AIService.shared.sendRequest(imageURL: imageURL)

        print("RAW AI TEXT:\n\(rawText)")

        guard let outer = try? JSONSerialization.jsonObject(with: Data(rawText.utf8)) as? [String: Any],
              let content = outer["content"] as? String else {
            throw NSError(domain: "Parse", code: 0, userInfo: [NSLocalizedDescriptionKey: "Missing 'content' field"])
        }

        let cleaned = content
            .replacingOccurrences(of: "```json", with: "")
            .replacingOccurrences(of: "```", with: "")
            .trimmingCharacters(in: .whitespacesAndNewlines)

        print("CLEANED JSON:\n\(cleaned)")

        let data = Data(cleaned.utf8)
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase

        return try decoder.decode(ExpenseAIResponse.self, from: data)
    }
}
